package com.gas.gm.dao;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

public abstract class GasApplicationDao<E> implements GasDao<E> {
	
	@PersistenceContext
	protected EntityManager entityManager;
	
	protected Class<E> type;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public GasApplicationDao() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		this.type = (Class) genericSuperclass.getActualTypeArguments()[0];
	}

	@Transactional
	public void persist(E entity) throws DataAccessException {
		entityManager.persist(entity);
	}

	@Transactional
	public void remove(E entity) throws DataAccessException {
		if(entityManager.contains(entity)){
			entityManager.remove(entity);
		}else{
			E toRemove=entityManager.merge(entity);
			entityManager.remove(toRemove);
		}
	}

	@Transactional
	public E merge(E entity) throws DataAccessException {
		E merged=entityManager.merge(entity);
		entityManager.flush();
		return merged;
	}

	
	public EntityManager getEntityManager() {
		return entityManager;
	}
	
	
	

}
